package com.brother.realtime;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.log4j.Logger;

public class ProcessorPool {
private List<RealTimeDataProcessor> pools = new CopyOnWriteArrayList<RealTimeDataProcessor>();

private static ProcessorPool instance;

private ProcessorPool(){
	
}

public List<RealTimeDataProcessor> getAll(){
	return pools;
}

public static ProcessorPool getInstance(){
	if(instance == null){
		instance = new ProcessorPool();
	}
	return instance;
}

public void addProcessor(RealTimeDataProcessor p){
	this.pools.add(p);
}

public void removeProcessor(RealTimeDataProcessor p){
	this.pools.remove(p);
	p.setStopped(true);
}

public void stopAll() {
	if(this.pools.size() == 0){
		return;
	}
	RealTimeDataProcessor p = null;
	while((p = this.pools.remove(0)) != null){
		
		p.setStopped(true);
		
		if(this.pools.size() == 0){
			break;
		}
	}
	
}



/**
 * @param userTrackerId  The IME Number.It will be removed.
 * @param realTimeDataProcessor The newest processor.
 */

public void removeProcessorByUserTrackerId(String userTrackerId,
		RealTimeDataProcessor rp) {
	RealTimeDataProcessor p  = null;
	for(RealTimeDataProcessor pp : this.pools){
		if(pp.getUserTrackerId() == null){
			continue;
		}
		if(pp.getUserTrackerId().equals(userTrackerId)){
			if(!pp.equals(rp)){
				p = pp;
				break;
			}
		}
	}
	if(p != null){
		if(log.isDebugEnabled()){
			log.debug("Removing processor "+p+" trackerId= "+p.getUserTrackerId());
		}
		this.pools.remove(p);
		p.setStopped(true);
		p.setReconnected(true);
	}
	
}

private Logger log = Logger.getLogger(this.getClass());

public RealTimeDataProcessor getProcessorByTrackerId(String trackerId){
	RealTimeDataProcessor p  = null;
	for(RealTimeDataProcessor pp : this.pools){
		//System.out.println(pp.getUserTrackerId()+"  trackerid:"+pp.getTracker().getTrackerid());
		if(pp.getTracker() != null && pp.getTracker().getTrackerid().equalsIgnoreCase(trackerId)){
			p = pp;
			break;
		}
	}
	return p;
	
}


}
